package com.tanjun.userservice.web.service.user.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.tanjun.common.enums.EnableStatusEnum;
import com.tanjun.common.enums.user.AdminUserTypeEnum;
import com.tanjun.common.exception.BizException;
import com.tanjun.common.utils.ConvertUntil;
import com.tanjun.common.utils.UserPasswordUntil;
import com.tanjun.userservice.web.service.input.AdminUserInput;
import com.tanjun.userservice.web.service.input.AdminUserRoleInput;
import com.tanjun.userservice.web.service.input.BaseAdminUserUniqueInput;
import com.tanjun.userservice.web.service.role.BaseAdminRoleService;
import com.tanjun.userservice.web.service.role.BaseAdminUserRoleService;
import com.tanjun.userservice.web.service.user.entity.BaseAdminDeptEntity;
import com.tanjun.userservice.web.service.user.entity.BaseAdminUserEntity;
import com.tanjun.userservice.web.service.user.mapper.BaseAdminUserMapper;
import com.tanjun.userservice.web.service.user.BaseAdminDeptService;
import com.tanjun.userservice.web.service.user.BaseAdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* @author tanjun
* @description 针对表【base_admin_user(系统用户)】的数据库操作Service实现
* @createDate 2024-12-03 21:44:43
*/
@Service
public class BaseAdminUserServiceImpl extends ServiceImpl<BaseAdminUserMapper, BaseAdminUserEntity>
    implements BaseAdminUserService {
    @Autowired
    private BaseAdminDeptService baseAdminDeptService;
    @Autowired
    private BaseAdminUserRoleService baseAdminUserRoleService;
    @Autowired
    private BaseAdminRoleService baseAdminRoleService;

    /**
     * 根据输入值判断是否有用户名、手机号或者邮箱等于给定的值
     *
     * @param key
     * @return
     */
    @Override
    public BaseAdminUserEntity getAdminUserByKey(String key) {
        return this.getOne(QueryChain.of(BaseAdminUserEntity.class)
                .eq(BaseAdminUserEntity::getUserName,key)
                .or(BaseAdminUserEntity::getEmail).eq(key)
                .or(BaseAdminUserEntity::getPhone)
                .eq(key)
        );
    }

    /**
     * 检查用户登录凭证是否唯一
     *
     * @param input 请求
     * @return 唯一返回true
     */
    @Override
    public void checkUserUnique(BaseAdminUserUniqueInput input) {
        //判断登录名是否重复
       boolean isHasCode=  this.count(QueryChain.of(BaseAdminUserEntity.class)
                .ne(BaseAdminUserEntity::getUserId,input.getNeqUserId(),input.getNeqUserId()!=null)
               .eq(BaseAdminUserEntity::getUserName,input.getUserName()))>0;
       if(isHasCode){
           throw new BizException("用户名重复");
       }
       if(StrUtil.isNotEmpty(input.getPhone())){ //判断手机号是否重复
           boolean isHasPhone=  this.count(QueryChain.of(BaseAdminUserEntity.class)
                   .ne(BaseAdminUserEntity::getUserId,input.getNeqUserId(),input.getNeqUserId()!=null)
                   .eq(BaseAdminUserEntity::getPhone,input.getPhone()))>0;
           if(isHasPhone){
               throw new BizException("手机号重复");
           }
       }
        if(StrUtil.isNotEmpty(input.getEmail())){ //判断邮箱是否重复
            boolean isHasEmail=  this.count(QueryChain.of(BaseAdminUserEntity.class)
                    .ne(BaseAdminUserEntity::getUserId,input.getNeqUserId(),input.getNeqUserId()!=null)
                    .eq(BaseAdminUserEntity::getEmail,input.getEmail()))>0;
            if(isHasEmail){
                throw new BizException("邮箱重复");
            }
        }
    }

    /**
     * 新增或修改用户信息
     * 新增用户的时候密码必填
     * 修改的时候不会修改用户密码
     *
     * @param input 用户信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdateUserBase(AdminUserInput input) {
        BaseAdminUserUniqueInput uniqueBo= ConvertUntil.convert(input,BaseAdminUserUniqueInput.class);
        uniqueBo.setNeqUserId(input.getUserId());
        checkUserUnique(uniqueBo); //验证登录凭证(登录名、手机号、邮箱)是否唯一
        if(input.getUserType()== AdminUserTypeEnum.SYSTEM) {
            BaseAdminDeptEntity dept = baseAdminDeptService.getById(input.getDeptId());
            if (dept == null || dept.getStatus() == EnableStatusEnum.NO) {
                throw new BizException("部门信息不存在或已被禁用");
            }
        }
        else { //todo 检查商户是否存在

        }

        BaseAdminUserEntity adminUser=ConvertUntil.convert(input, BaseAdminUserEntity.class);
        if(adminUser.getUserId()!=null){ //修改用户
            adminUser.setUpdater(input.getOperator());
            this.updateById(adminUser);
        }
        else { //新增用户
            Assert.notNull(input.getOriPassword(),"未设置密码");
            adminUser.setCreator(input.getOperator());
            String salt= UserPasswordUntil.generateSalt();
            String password=UserPasswordUntil.encode(input.getOriPassword(),salt);
            adminUser.setPwd(password);
            adminUser.setSalt(salt);
            this.save(adminUser);
        }

        //保存用户权限
        AdminUserRoleInput userRoleBo=new AdminUserRoleInput();
        userRoleBo.setOperator(input.getOperator());
        userRoleBo.setUserId(adminUser.getUserId());
        userRoleBo.setRoleIdList(input.getRoleIdList());
        baseAdminUserRoleService.saveUserRoles(userRoleBo);
    }

    /**
     * 根据userId 获取用户信息
     *
     * @param userId 用户id
     * @return 用户信息
     */
    @Override
    public BaseAdminUserEntity getAdminUserByUserId(Long userId) {
        return this.getById(userId);
    }

    /**
     * 删除用户信息
     *
     * @param userId 用户id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delAdminUserByUserId(Long userId) {
        if(getAdminUserByUserId(userId)==null){
            throw new BizException("用户信息不存在");
        }
        this.removeById(userId);
        
        //删除用户角色信息
        baseAdminUserRoleService.delUserRole(userId);
    }

    /**
     * 重置密码
     *
     * @param userId   用户id
     * @param password 密码
     */
    @Override
    public void resetPassword(Long userId, String password) {
        BaseAdminUserEntity adminUser=this.getAdminUserByUserId(userId);
        if(adminUser==null){
            throw new BizException("用户信息不存在");
        }
        String salt= UserPasswordUntil.generateSalt();
        String encodePassword=UserPasswordUntil.encode(password,salt);
     UpdateChain.of(BaseAdminUserEntity.class)
                .set(BaseAdminUserEntity::getSalt,salt)
                .set(BaseAdminUserEntity::getPwd,encodePassword)
                .eq(BaseAdminUserEntity::getUserId,userId)
             .update();

    }


}




